//
//  MeViewController.swift
//  LongTermInsurance
//
//  Created by DYD on 2018/11/9.
//  Copyright © 2018 HeChao. All rights reserved.
//

import UIKit
import Rswift
import Kingfisher
import Rswift
class MeViewController: BaseTableViewController {

    var cacheSzie = 0.0
    
    lazy var headerView: MeHeaderView = {
        let view = Bundle.main.loadNibNamed("MeHeaderView", owner: nil
            , options: nil)!.last as! MeHeaderView
        view.frame = CGRect(x: 0, y: 0, width: DeviceInfo.screenWidth, height: 120)
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "我的"
        view.backgroundColor = .white
        tableView.register(UINib(nibName: "MeInfoTableViewCell", bundle: nil), forCellReuseIdentifier: "MeInfoTableViewCell")
        tableView.register(UINib(nibName: "MeTableViewCell", bundle: nil), forCellReuseIdentifier: "MeTableViewCell")
        
        tableView.tableHeaderView = headerView
        tableView.rowHeight = 50.0
        
        calculateDiskCacheSize()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tableView.reloadData()
        
        if let info = MyselfSingleton.shared.userInfo {
            headerView.avatarImageView.image = info.sex == "男" ? R.image.gender_male() : R.image.gender_female()
            headerView.nameLabel.text = info.name
            headerView.numberLabel.text = info.personNum
        }
        
        
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 6
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MeTableViewCell", for: indexPath) as! MeTableViewCell
            cell.nameLabel.text = "意见反馈"
            cell.iconImageView.image = R.image.me_feedback()
            return cell
        } else if indexPath.row == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MeInfoTableViewCell", for: indexPath) as! MeInfoTableViewCell
            cell.titleLabel.text = "清空缓存"
            cell.iconImageView.image = R.image.me_clear()
            cell.detailLabel.text = String(format: "%.2f MB", cacheSzie)
            
            return cell
        } else if indexPath.row == 2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MeInfoTableViewCell", for: indexPath) as! MeInfoTableViewCell
            cell.titleLabel.text = "当前版本"
            var appVersion = ""
            if let v = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
            {
                appVersion = v
            }
            cell.detailLabel.text = appVersion
            cell.iconImageView.image = R.image.me_version()
            return cell
        } else if indexPath.row == 3 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MeTableViewCell", for: indexPath) as! MeTableViewCell
            cell.nameLabel.text = "关于我们"
            cell.iconImageView.image = R.image.me_about()
            return cell
        } else if indexPath.row == 4 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MeTableViewCell", for: indexPath) as! MeTableViewCell
            cell.nameLabel.text = "修改密码"
            cell.iconImageView.image = R.image.me_modfiy()
            return cell
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "MeTableViewCell", for: indexPath) as! MeTableViewCell
        cell.nameLabel.text = "退出登录"
        cell.iconImageView.image = R.image.me_exit()
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 0 {
            let fb = FeedBackViewController()
            navigationController?.pushViewController(fb, animated: true)
            return
        } else if indexPath.row == 1 {
            cleanCache()
            return
        } else if indexPath.row == 2 {
            return
        } else if indexPath.row == 3 {
            let fb = AboutUsViewController()
            navigationController?.pushViewController(fb, animated: true)
            return
        } else if indexPath.row == 4 {
            navigationController?.pushViewController(ChangePasswordViewController(), animated: true)
            return
        } else {
            MyselfSingleton.shared.logOutcClean()
            UIManager.shared.tabBarController.showLoginViewController()
            UIManager.shared.tabBarController.selectedIndex = TabBarIndex.homePage.rawValue
        }
    }
}

extension MeViewController {
    
    
    func calculateDiskCacheSize() {
        self.cacheSzie = 0.0
        KingfisherManager.shared.cache.calculateDiskCacheSize {[weak self] (size) in
            if let strongSelf = self{
                let mb = Double(size) / 1024.0 / 1024.0
                CDUtility.log("Kingfisher Cache Size: \(mb)")
                strongSelf.cacheSzie += mb
                strongSelf.tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: .none)
            }
        }
        
        SDWebImageManager.shared().imageCache?.calculateSize(completionBlock: {[weak self] (fileCount, totalSize) in
            if let strongSelf = self{
                let mb = Double(totalSize) / 1024.0 / 1024.0
                CDUtility.log("SDWebImage Cache Size: \(mb)")
                strongSelf.cacheSzie += mb
                strongSelf.tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: .none)
            }
        })
    }
    
    func cleanCache() {
        UserDefaults.standard.set(nil, forKey: CDUserDefaultKey.homeCareFileKey)
        UserDefaults.standard.set(nil, forKey: CDUserDefaultKey.orgCareFileKey)
        
        KingfisherManager.shared.cache.clearDiskCache()
        SDWebImageManager.shared().imageCache?.clearMemory()
        CDUtility.showMSG(message: "清理成功")
        calculateDiskCacheSize()
    }
}
